/**
 * 工具栏管理 - 符合utility.mdr规则
 */
import { toolIcons, toolSeparator } from './tool-icons.js';
import { dragManager } from '../globalMgr.js';

export class ToolbarManager {
    private activeTool: string = 'select'; // 默认选中选择工具
    private activeConnectionStyle: string = 'connection_straight';
    private toolbar: HTMLDivElement;

    constructor(container: HTMLElement) {
        this.toolbar = document.createElement('div');
        this.toolbar.className = 'circuit-toolbar';
        
        // 工具栏样式
        this.toolbar.style.display = 'flex';
        this.toolbar.style.alignItems = 'center';
        this.toolbar.style.gap = '0px'; // 使用margin控制间距
        
        container.appendChild(this.toolbar);
        this.setupTools();
    }

    private setupTools(): void {
        const tools = ['select', 'resistor', 'capacitor', 'wire', 'voltage_source', 'current_source'];
        
        tools.forEach((tool, index) => {
            // 添加分隔符（除了第一个工具）
            if (index > 0) {
                const separator = document.createElement('div');
                separator.innerHTML = toolSeparator;
                this.toolbar.appendChild(separator.firstChild as HTMLElement);
            }

            const toolData = toolIcons[tool];
            if (toolData) {
                const btn = document.createElement('button');
                btn.className = 'tool-button';
                btn.setAttribute('data-tool', tool); // 添加标识属性
                btn.innerHTML = toolData.svg;
                btn.title = toolData.title; // hover时显示工具名称
                
                // 按钮样式
                btn.style.display = 'flex';
                btn.style.alignItems = 'center';
                btn.style.justifyContent = 'center';
                btn.style.width = '32px';
                btn.style.height = '32px';
                btn.style.padding = '4px';
                btn.style.border = '1px solid transparent';
                btn.style.borderRadius = '4px';
                btn.style.background = this.activeTool === tool ? '#e6f3ff' : 'transparent';
                btn.style.cursor = 'pointer';
                btn.style.transition = 'all 0.2s ease';
                
                // 如果是当前激活的工具，显示选中状态
                if (this.activeTool === tool) {
                    btn.style.borderColor = '#007acc';
                }
                
                // hover效果
                btn.addEventListener('mouseenter', () => {
                    if (this.activeTool !== tool) {
                        btn.style.borderColor = '#007acc';
                        btn.style.background = '#f0f8ff';
                    }
                });
                
                btn.addEventListener('mouseleave', () => {
                    if (this.activeTool !== tool) {
                        btn.style.borderColor = 'transparent';
                        btn.style.background = 'transparent';
                    }
                });
                
                btn.addEventListener('click', () => this.setActiveTool(tool));
                
                // 添加拖拽支持
                dragManager.setupDrag(btn, tool);
                
                this.toolbar.appendChild(btn);
            }
        });

        // 添加分隔符
        const separator = document.createElement('div');
        separator.innerHTML = toolSeparator;
        this.toolbar.appendChild(separator.firstChild as HTMLElement);

        // 添加连线样式按钮组
        this.setupConnectionStyleButtons();
    }

    private setupConnectionStyleButtons(): void {
        const connectionStyles = ['connection_straight', 'connection_bezier', 'connection_handdrawn'];
        
        connectionStyles.forEach((style, index) => {
            const toolData = toolIcons[style];
            if (toolData) {
                const btn = document.createElement('button');
                btn.className = 'connection-style-button';
                btn.setAttribute('data-connection-style', style); // 添加标识属性
                btn.innerHTML = toolData.svg;
                btn.title = toolData.title;
                
                // 按钮样式
                btn.style.display = 'flex';
                btn.style.alignItems = 'center';
                btn.style.justifyContent = 'center';
                btn.style.width = '32px';
                btn.style.height = '32px';
                btn.style.padding = '4px';
                btn.style.border = '1px solid transparent';
                btn.style.borderRadius = '4px';
                btn.style.background = this.activeConnectionStyle === style ? '#e6f3ff' : 'transparent';
                btn.style.cursor = 'pointer';
                btn.style.transition = 'all 0.2s ease';
                
                // 如果是当前激活的样式，显示选中状态
                if (this.activeConnectionStyle === style) {
                    btn.style.borderColor = '#007acc';
                }
                
                // hover效果
                btn.addEventListener('mouseenter', () => {
                    if (this.activeConnectionStyle !== style) {
                        btn.style.borderColor = '#007acc';
                        btn.style.background = '#f0f8ff';
                    }
                });
                
                btn.addEventListener('mouseleave', () => {
                    if (this.activeConnectionStyle !== style) {
                        btn.style.borderColor = 'transparent';
                        btn.style.background = 'transparent';
                    }
                });
                
                btn.addEventListener('click', () => this.setActiveConnectionStyle(style));
                
                this.toolbar.appendChild(btn);
            }
        });
    }

    private setActiveTool(tool: string): void {
        this.activeTool = tool;
        
        // 更新所有工具按钮的视觉状态
        const toolButtons = this.toolbar.querySelectorAll('.tool-button');
        toolButtons.forEach(btn => {
            const btnElement = btn as HTMLButtonElement;
            const btnTool = btnElement.getAttribute('data-tool');
            
            if (btnTool === tool) {
                // 激活状态
                btnElement.style.borderColor = '#007acc';
                btnElement.style.background = '#e6f3ff';
            } else {
                // 非激活状态
                btnElement.style.borderColor = 'transparent';
                btnElement.style.background = 'transparent';
            }
        });
        
        window.dispatchEvent(new CustomEvent('circuit-editor:tool-selected', { 
            detail: { tool }
        }));
    }

    private setActiveConnectionStyle(style: string): void {
        console.log('Setting active connection style to:', style);
        this.activeConnectionStyle = style;
        
        // 更新所有连线样式按钮的视觉状态
        const connectionButtons = this.toolbar.querySelectorAll('.connection-style-button');
        console.log('Found connection buttons:', connectionButtons.length);
        
        connectionButtons.forEach(btn => {
            const btnElement = btn as HTMLButtonElement;
            const btnStyle = btnElement.getAttribute('data-connection-style');
            console.log('Button style:', btnStyle, 'Target style:', style);
            
            if (btnStyle === style) {
                // 激活状态
                btnElement.style.borderColor = '#007acc';
                btnElement.style.background = '#e6f3ff';
                console.log('Activated button for style:', style);
            } else {
                // 非激活状态
                btnElement.style.borderColor = 'transparent';
                btnElement.style.background = 'transparent';
            }
        });
        
        // 发送连线样式变更事件
        console.log('Dispatching connection style changed event with style:', style);
        window.dispatchEvent(new CustomEvent('circuit-editor:connection-style-changed', { 
            detail: { style }
        }));
    }
}